package org.jili.novoland.scene;

import org.jili.novoland.listener.ControlListener;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class GameScene extends SurfaceView implements Callback, Runnable {

    private Thread gameThread;
    private SurfaceHolder holder;

    private Paint paint=new Paint();
    private ControlListener controlListener;
    
    final static private long MILLIS_PER_TICK = 10;
    private long timeTaken = 0;

    public GameScene(Context context) {
        super(context);
        setFocusable(true);
        holder = getHolder();
        holder.addCallback(this);

    }
    public void setController(ControlListener listener){
        this.controlListener = listener;
        super.setOnTouchListener(listener);
        
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub

    }

    public void surfaceCreated(SurfaceHolder holder) {
        start();
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        stop();

    }

    public class BattleFieldThread extends Thread {

    }

    private synchronized void start() {
        gameThread = new Thread(this);
        gameThread.start();
    }

    private synchronized void stop() {
        gameThread = null;
    }

    private void clearBackground(Canvas canvas){
        paint.setColor(0xFF808080);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(0,0,canvas.getWidth(),canvas.getHeight(),paint);

    }

    public void run() {

        try {
            while (Thread.currentThread() == gameThread) {
                long startTime = System.currentTimeMillis();
                if (isShown()) {
                    Canvas canvas = holder.lockCanvas();
//                    resourceManager.getBattleFieldMap().setSceneSize(canvas.getWidth(), canvas.getHeight());
                    clearBackground(canvas);
                    controlListener.getLayerManager().paint(canvas);
                    holder.unlockCanvasAndPost(canvas);
                }
                timeTaken = System.currentTimeMillis() - startTime;
                if (timeTaken < MILLIS_PER_TICK) {
                    synchronized (this) {
                        if (MILLIS_PER_TICK > timeTaken) {
                            wait(MILLIS_PER_TICK - timeTaken);
                            timeTaken = System.currentTimeMillis() - startTime;
                        }
                    }
                } else {
                    Thread.yield();
                }
            }
        } catch (InterruptedException e) {
        }

    }
}
